#include "TIM_InputCapture.h"
#include "stm32f10x.h"


uint16_t frequency;

// 占空比 %
uint16_t duty_cycle;

void init_capture_pwm(void){
    
    // 开启 TIM2 定时器时钟
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);

    TIM_InternalClockConfig(TIM2);   
    
    GPIO_Init(GPIOA,&(GPIO_InitTypeDef){
        .GPIO_Pin=GPIO_Pin_0,
        .GPIO_Mode = GPIO_Mode_IN_FLOATING,
        .GPIO_Speed=GPIO_Speed_50MHz
     
    });

    TIM_TimeBaseInit(TIM2,&(TIM_TimeBaseInitTypeDef){
        
        .TIM_Prescaler = 72,
        .TIM_CounterMode = TIM_CounterMode_Up,
        .TIM_Period = 0xffff, // 自动重装寄存器取最大值，防止 count 被 重置
        .TIM_ClockDivision=TIM_CKD_DIV1,
        
    });
    
    // 配置输入捕获 测量 pwm 频率
    TIM_ICInit(TIM2,&(TIM_ICInitTypeDef){
        
        .TIM_Channel=TIM_Channel_1, // 输入通道
        .TIM_ICPolarity=TIM_ICPolarity_Rising, // 上升沿 触发
        .TIM_ICSelection=TIM_ICSelection_DirectTI,  // 选择直连通道作为输入，即 TI1
        .TIM_ICPrescaler=TIM_ICPSC_DIV1,
        .TIM_ICFilter=0
    });
  
    TIM_SelectInputTrigger(TIM2,TIM_TS_TI1FP1);
    
 //   TIM_SelectOutputTrigger(TIM2,TIM_TRGOSource_Reset);
    
    TIM_SelectSlaveMode(TIM2,TIM_SlaveMode_Reset);
    
    // 记录下降沿来测量占空比
    
    
    TIM_ICInit(TIM2,&(TIM_ICInitTypeDef){
        
        .TIM_Channel=TIM_Channel_2, // 输入通道
        .TIM_ICPolarity=TIM_ICPolarity_Falling, // 下降沿 触发
        // 选择交叉通道作为输入 即 TI1
        // 这样可以和 通道一共用一个引脚
        .TIM_ICSelection=TIM_ICSelection_IndirectTI, 
        .TIM_ICPrescaler=TIM_ICPSC_DIV1,
        .TIM_ICFilter=0
    });
    
    // 启用通道一
    TIM_CCxCmd(TIM2,TIM_Channel_1,TIM_CCx_Enable);
    
    // 启用 capture compare register 的中断 
    TIM_ITConfig(TIM2,TIM_IT_CC1,ENABLE);
    
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
    
    NVIC_Init(&(NVIC_InitTypeDef){
    
           .NVIC_IRQChannel= TIM2_IRQn ,
           .NVIC_IRQChannelPreemptionPriority = 1,
           .NVIC_IRQChannelSubPriority = 2,
           .NVIC_IRQChannelCmd = ENABLE 
    });
    
    TIM_Cmd(TIM2,ENABLE );
}

uint16_t paule_width_ccr_val;

uint16_t feq_ccr_val;

void TIM2_IRQHandler(void){
   /* 
    if(TIM_GetITStatus(TIM2,TIM_IT_CC2)==SET){
   
        TIM_ClearITPendingBit(TIM2,TIM_IT_CC2);
    }
*/
 
    if(TIM_GetITStatus(TIM2,TIM_IT_CC1)==SET){
    
        // 手动获取捕获比较寄存器的值
        feq_ccr_val = TIM_GetCapture1(TIM2);
        
        frequency = 1000000/ feq_ccr_val;
        
        //TIM_SetCompare1(TIM2,0); 输入模式下无法设置CCR
        
         // 测量占空比
        paule_width_ccr_val = TIM_GetCapture2(TIM2);

        
        duty_cycle= 100* paule_width_ccr_val/feq_ccr_val;
        
        // 计数器清零，手动清0误差大，上面使用了slave模式来自动清0
        //TIM_SetCounter(TIM2,0);
    
        TIM_ClearITPendingBit(TIM2,TIM_IT_CC1);
    }
    

}


